package cn.kgc.javaweb.servlet;

import cn.hutool.captcha.LineCaptcha;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import cn.kgc.javaweb.entity.SysUser;
import cn.kgc.javaweb.service.UserService;
import cn.kgc.javaweb.service.impl.UserServiceImpl;
import cn.kgc.javaweb.utils.ResponseResultUtil;
import cn.kgc.javaweb.utils.ResponseUtil;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;

/**
 * @author: mosin
 * @version: v1.0  2022/6/7
 * 用户请求控制类
 */
@WebServlet("/user")
public class UserServlet extends BaseServlet {

    private UserService userService = new UserServiceImpl();

    //用户登录
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        System.out.println("login");
        //获取前端登录参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String code = req.getParameter("code");


        //获取session中的验证码
        String captcha = (String) req.getSession().getAttribute("code");

        // 设置响应的格式为json
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        String info = null;
        //比较验证码
        if (captcha.equals(code)) {
            //登录校验
            ResponseResultUtil responseResultUtil = userService.login(username, SecureUtil.md5(password));
            if (responseResultUtil.getData() != null) {
                SysUser user = (SysUser) responseResultUtil.getData();
                req.getSession().setAttribute("user", user);
            }
            info = JSONUtil.toJsonStr(responseResultUtil);
        } else { //验证码不正确
            ResponseResultUtil responseResultUtil = new ResponseResultUtil();
            responseResultUtil.setCode(500);
            responseResultUtil.setMsg("验证码错误！！！");
            //将 java对象转换为json格式的数据
            info = JSONUtil.toJsonStr(responseResultUtil);
        }
        writer.write(info);
        writer.close();
    }


    //注册方法
    protected void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String username = req.getParameter("username");
        String password = req.getParameter("password");

        //密码加密  MD5
        String securePassword = SecureUtil.md5(password);

        boolean b = userService.register(username, securePassword);
        HashMap<String, Object> map = new HashMap<>();
        if (b) {
            map.put("code", 0);
            map.put("msg", "注册成功！！");

        } else {
            map.put("code", 500);
            map.put("msg", "注册失败！！");
        }

        resp.setContentType("application/json;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.write(JSONUtil.toJsonStr(map));
        writer.close();

    }

    //生成登录页面的验证码
    protected void captcha(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        LineCaptcha lineCaptcha = new LineCaptcha(260, 100, 4, 5);
        //获取生成的验证码 保存 session
        String code = lineCaptcha.getCode();
        System.out.println("code = " + code);
        req.getSession().setAttribute("code", code);

        //获取输出流 将图像验证码 写出到登录页
        ServletOutputStream outputStream = resp.getOutputStream();
        lineCaptcha.write(outputStream);
        //释放资源
        outputStream.close();
    }

    //修改密码
    protected void resetpassword(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String oldpwd = req.getParameter("oldpwd");
        String newpwd = req.getParameter("newpwd");

        //获取当前用户的密码
        SysUser user = (SysUser) req.getSession().getAttribute("user");
        String password = user.getPassword(); //加密后的密码
        //获取用户的id 用于修改用户的条件
        long id = user.getId();

        HashMap<String, Object> map = new HashMap<>();

        if (SecureUtil.md5(oldpwd).equals(password)) {
            //执行修改密码操作
            boolean b = userService.resetPasswordById(id, SecureUtil.md5(newpwd));
            if (b) {
                map.put("code", 0);
                map.put("msg", "密码修改成功");
            } else {
                map.put("code", 500);
                map.put("msg", "密码修改失败");
            }
        } else { // 原始密码不正确 修改密码失败
            map.put("code", 500);
            map.put("msg", "原始密码不正确");
        }

        ResponseUtil.write(resp, map);
    }

    //退出登录
    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //销毁当前请求对应的session
        HashMap<String, Object> map = new HashMap<>();
        try {
            req.getSession().invalidate();
            map.put("code", 0);
            map.put("msg", "退出登录成功");
        } catch (Exception e) {
            e.printStackTrace();
            map.put("code", 500);
            map.put("msg", "退出登录失败");
        }

        resp.setContentType("application/json;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        writer.write(JSONUtil.toJsonStr(map));
        writer.close();
    }

    // 分页查询
    protected void selectAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String page = req.getParameter("page");
        String limit = req.getParameter("limit");
        ResponseResultUtil responseResultUtil = userService.selectAll(page, limit);

        ResponseUtil.write(resp, responseResultUtil);

    }

    //根据id删除用户
    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Integer id = Integer.parseInt(req.getParameter("id"));

        HashMap<String, Object> map = new HashMap<>();
        boolean b = userService.deleteById(id);
        if (b) {
            map.put("code", 0);
            map.put("msg", "删除成功");

        } else {
            map.put("code", 500);
            map.put("msg", "删除失败");
        }

        ResponseUtil.write(resp, map);

    }

    //重置密码

    protected void replacepwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        Integer id = Integer.parseInt(req.getParameter("id"));

        boolean b = userService.updatePwd(id);
        HashMap<String, Object> map = new HashMap<>();

        if (b) {
            map.put("code", 0);
            map.put("msg", "重置密码成功");

        } else {
            map.put("code", 500);
            map.put("msg", "重置密码失败");
        }

        ResponseUtil.write(resp, map);

    }


    //添加用户
    protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String username = req.getParameter("username");
        String nickName = req.getParameter("nickName");
        Integer sex = Integer.parseInt(req.getParameter("sex"));
        Integer roleId = Integer.parseInt(req.getParameter("roleId"));
        String phone = req.getParameter("phone");

        //将数据封装成user对象
        SysUser user = SysUser.builder().nickName(nickName).password(SecureUtil.md5("123456")).phone(phone).roleId(roleId).sex(sex).username(username).build();

        boolean b = userService.selectByUserName(username);
        HashMap<String, Object> map = new HashMap<>();
        if (b) {
            map.put("code", 500);
            map.put("msg", "用户名已被占用");
        } else {

            if (userService.addUser(user)) {
                map.put("code", 0);
                map.put("msg", "添加用户成功");

            }else{
                map.put("code", 500);
                map.put("msg", "添加用户失败！！");
            }
        }
        ResponseUtil.write(resp, map);
    }

    //更新用户
    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


        String username = req.getParameter("username");
        String nickName = req.getParameter("nickName");
        Integer sex = Integer.parseInt(req.getParameter("sex"));
        Integer roleId = Integer.parseInt(req.getParameter("roleId"));
        String phone = req.getParameter("phone");

        //将数据封装成user对象
        SysUser user = SysUser.builder().nickName(nickName).password(SecureUtil.md5("123456")).phone(phone).roleId(roleId).sex(sex).username(username).build();

         boolean b =  userService.updateUser(user);
        HashMap<String, Object> map = new HashMap<>();

         if (b) {
             map.put("code", 0);
             map.put("msg", "修改用户成功");
         }else{
             map.put("code", 500);
             map.put("msg", "修改用户失败！！");
         }
         ResponseUtil.write(resp, map);
    }

    //更新用户
    protected void search(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{

        Integer page = Integer.parseInt(req.getParameter("page")) ;
        Integer limit = Integer.parseInt(req.getParameter("limit")) ;
        String username = req.getParameter("username");
        ResponseResultUtil  users = userService.searchByUserName(username,page,limit);
        ResponseUtil.write(resp, users);
    }

    //更新用户状态
    protected void state(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{


        String id = req.getParameter("id");
        Integer state = Integer.parseInt(req.getParameter("state")) ;

        System.out.println("state = " + state);
        System.out.println("id = " + id);

        HashMap<String, Object> map = new HashMap<>();
        // TODO  根据id 更新用户的状态
         boolean b =  userService.updateState(id,state);

        //  TODO  根据更新的结果 响应数据   map
        if(b){
            map.put("code", 0);
            map.put("msg", "状态更新成功");
        }else{
            map.put("code", 500);
            map.put("msg", "状态更新失败");
        }
        ResponseUtil.write(resp,map);
    }


    //批量删除
    protected void deleteMore(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{

        String ids = req.getParameter("ids");
        System.out.println("ids = " + ids);
        String[] split = ids.split(",");
        HashMap<String, Object> map = new HashMap<>();
        try {
            for (String s : split) {
                userService.deleteById(Integer.parseInt(s));
            }
            map.put("code", 0);
            map.put("msg", "删除成功");
        } catch (NumberFormatException e) {
            e.printStackTrace();
            map.put("code", 500);
            map.put("msg", "删除失败!");
        }

        ResponseUtil.write(resp, map);

    }

}
